package com.yhp.dao.impl;

import com.yhp.bean.Role;
import com.yhp.dao.RoleDao;
import com.yhp.util.DBUtilsPlus;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoleDaoImpl extends DBUtilsPlus implements RoleDao {
    @Override
    public List<Role> selectAll() {
        List<Role> rolelist=new ArrayList<Role>();
        try {
            String sql="select * from role";
            resultSet = selectDB(sql, null);
            while(resultSet.next()){
                Role role = new Role();
                role.setRoleId(resultSet.getInt("roleid"));
                role.setRoleName(resultSet.getString("rolename"));
                rolelist.add(role);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return rolelist;
    }

    @Override
    public int deleteById(int id) {
        int i = 0;
        try {
            String sql="delete from role where roleid=?";
            List params=new ArrayList();
            params.add(id);
            i = updateDB(sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return i;
    }

    @Override
    public int updateRole(Role role) {
        int i =0;
        try {
            String sql="update role set rolename=? where roleid=?";
            List params=new ArrayList();
            params.add(role.getRoleName());
            params.add(role.getRoleId());
            i = updateDB(sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return i;
    }

    @Override
    public int insertRole(Role role) {
        int i = 0;
        try {
            String sql="insert into role(roleid,rolename) values(null,?)";
            List params=new ArrayList();
            params.add(role.getRoleName());
            i = updateDB(sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return i;
    }

    @Override
    public Role findById(int id) {
        Role role=null;
        try {
            String sql="select * from role where roleid=?";
            List params=new ArrayList();
            params.add(id);
            resultSet = selectDB(sql, params);
            while(resultSet.next()){
                role=new Role();
                role.setRoleId(resultSet.getInt("roleid"));
                role.setRoleName(resultSet.getString("rolename"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return role;
    }
}
